<!-- views/Home.vue -->
<template>
  <div class="home-container">
    <!-- 修改后的功能入口区 -->
    <el-row class="quick-access" :gutter="20">
      <el-col
          v-for="item in menuItems"
          :key="item.path"
          class="menu-col"
      >
        <el-card
            shadow="hover"
            class="access-card horizontal-card"
            @click="router.push(item.path)"
        >
          <div class="horizontal-content">
            <el-icon :size="28"><component :is="item.icon" /></el-icon>
            <span class="menu-title">{{ item.title }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 训练概览区 -->
    <el-row :gutter="20" class="overview-section">
      <!-- 左列 -->
      <el-col :span="16">
        <!-- 训练指标趋势 -->
        <el-card header="训练指标趋势" class="chart-card">
          <div class="chart-header">
            <span class="time-range">最近1小时数据</span>
          </div>
          <line-chart :data="trainingMetrics"/>
        </el-card>
        <!-- 客户端监测 -->
        <el-card header="客户端监测" class="mt-4">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="anomaly-metric">
                <h4>异常参数更新次数</h4>
                <el-statistic :value="maliciousActivities.length" />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="anomaly-metric">
                <h4>当前可疑客户端</h4>
                <el-statistic
                    :value="suspiciousClients"
                    class="danger-text"
                />
              </div>
            </el-col>
          </el-row>
        </el-card>
        <!-- 图表行 -->
        <el-row :gutter="20" class="chart-row">
          <el-col :span="12">
            <el-card header="客户端类型分布" class="chart-card">
              <pie-chart :data="clientDistribution" />
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card header="资源使用率" class="chart-card">
              <bar-chart :data="resourceUsage" />
            </el-card>
          </el-col>
        </el-row>
      </el-col>

      <!-- 右列 -->
      <el-col :span="8">
        <el-card header="行为日志" class="malicious-log">
          <div class="log-container">
            <div
                v-for="(log, index) in maliciousActivities"
                :key="index"
                class="log-entry"
                :class="log.severity"
            >
              <span class="timestamp">{{ log.timestamp }}</span>
              <span class="message">{{ log.message }}</span>
              <el-tag
                  v-if="log.severity === 'high'"
                  type="danger"
                  size="small"
              >
                严重
              </el-tag>
              <el-tag
                  v-else-if="log.severity === 'medium'"
                  type="warning"
                  size="small"
              >
                警告
              </el-tag>
            </div>
          </div>
        </el-card>
        <!-- 实时状态 -->
        <el-card header="实时状态概览">
          <div class="status-items">
            <div class="status-item">
              <label>当前准确率：</label>
              <el-tag type="success">{{ currentAccuracy }}%</el-tag>
            </div>
            <div class="status-item">
              <label>当前损失值：</label>
              <el-tag type="warning">{{ currentLoss.toFixed(2) }}</el-tag>
            </div>
            <div class="status-item">
              <label>在线客户端：</label>
              <el-tag>{{ onlineClients }}/{{ totalClients }}</el-tag>
            </div>
            <div class="status-item">
              <label>训练轮次：</label>
              <el-tag type="info">Epoch {{ currentEpoch }}</el-tag>
            </div>
          </div>
        </el-card>

        <!-- 训练进度 -->
        <el-card header="训练阶段进度" class="mt-4 chart-card">
          <progress-chart :data="trainingProgress" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import {
  User,
  Warning,
  Histogram,
  Setting
} from '@element-plus/icons-vue'
import LineChart from '@/components/charts/LineCharts.vue'
import PieChart from '@/components/charts/PieChart.vue'
import ProgressChart from '@/components/charts/ProgressChart.vue'
import BarChart from "@/components/charts/BarChart.vue";

const router = useRouter()

// 功能菜单配置
const menuItems = ref([
  {
    title: '客户端分析',
    icon: User,
    path: '/clients'
  },
  {
    title: '安全中心',
    icon: Warning,
    path: '/security'
  },
  {
    title: '模型版本',
    icon: Histogram,
    path: '/versions'
  },
  {
    title: '系统设置',
    icon: Setting,
    path: '/settings'
  },
])

// 训练指标数据
const trainingMetrics = ref({
  accuracy: generateRandomData(0.75, 0.15, 10),
  loss: generateRandomData(1.8, 0.5, 10)
})

// 图表数据
const clientDistribution = ref([
  { name: '移动端', value: 68 },
  { name: '桌面端', value: 25 },
  { name: 'IoT设备', value: 7 }
])

const resourceUsage = ref([
  { name: 'CPU', value: 80 },
  { name: '内存', value: 65 },
  { name: '带宽', value: 45 }
])

const trainingProgress = ref([
  { stage: '数据准备', progress: 100 },
  { stage: '初始化训练', progress: 85 },
  { stage: '联邦聚合', progress: 60 },
  { stage: '模型验证', progress: 30 }
])

// 实时状态数据
const currentAccuracy = ref(82.34)
const currentLoss = ref(1.25)
const onlineClients = ref(23)
const totalClients = ref(30)
const currentEpoch = ref(15)

// 数据生成函数
function generateRandomData(base: number, range: number, count: number) {
  return Array.from({length: count}, (_, i) => ({
    time: `Epoch ${i+1}`,
    value: base + Math.random() * range
  }))
}
// 客户端数据
const maliciousActivities = ref([
  {
    timestamp: '10:23:15',
    message: '客户端#23 参数更新异常（偏离均值3σ）',
    severity: 'high'
  },
  {
    timestamp: '10:22:50',
    message: '客户端#17 响应延迟异常（1200ms）',
    severity: 'medium'
  },
]);

const suspiciousClients = ref(3);

// 模拟日志生成
setInterval(() => {
  if(Math.random() > 0.8) {
    maliciousActivities.value.unshift({
      timestamp: new Date().toLocaleTimeString(),
      message: `客户端#${Math.floor(Math.random()*30)} 检测到可疑参数更新`,
      severity: Math.random() > 0.5 ? 'high' : 'medium'
    });

    // 保持日志数量不超过20条
    if(maliciousActivities.value.length > 20) {
      maliciousActivities.value.pop();
    }
  }
}, 3000);
</script>

<style scoped>
/* 横向排列样式 */
.quick-access {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  padding-bottom: 8px; /* 留出滚动条空间 */
}

.menu-col {
  flex: 0 0 auto;
  width: calc(25% - 20px); /* 4个等宽卡片，考虑gutter间距 */
  min-width: 180px; /* 最小宽度保证内容可见 */
}

.horizontal-card {
  height: 80px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.horizontal-content {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0 16px;
}

.menu-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.home-container {
  padding: 20px;
}

.quick-access {
  margin-bottom: 20px;
}

.access-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.2s;
}

.access-card:hover {
  transform: translateY(-5px);
}

.card-content {
  text-align: center;
  padding: 20px 0;
}

.overview-section {
  margin-top: 20px;
}

.status-items {
  display: grid;
  gap: 16px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: var(--el-bg-color-page);
  border-radius: 4px;
}

.status-item label {
  font-weight: 500;
  color: var(--el-text-color-regular);
}

/* 图表样式 */
.chart-card {
  height: 400px;
  margin-bottom: 20px;
}

.chart-row {
  margin-top: 20px;
}

.mt-4 {
  margin-top: 1rem;
}

.malicious-log {
  height: 300px;
  margin-bottom: 20px;
}

.log-container {
  height: 250px;
  overflow-y: auto;
  font-family: monospace;
}

.log-entry {
  padding: 8px 12px;
  margin: 4px 0;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.timestamp {
  color: var(--el-text-color-secondary);
  min-width: 70px;
}

.danger-text {
  color: var(--el-color-danger);
}

.anomaly-metric {
  text-align: center;
  padding: 15px;
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
}

.anomaly-metric h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .menu-col {
    width: calc(25% - 20px);
  }
}

@media (max-width: 992px) {
  .menu-col {
    width: calc(33.333% - 20px);
  }
}

@media (max-width: 768px) {
  .quick-access {
    flex-wrap: wrap;
    gap: 12px;
  }

  .menu-col {
    width: 100%;
    min-width: auto;
  }

  .horizontal-card {
    height: auto;
    padding: 12px 0;
  }

  .horizontal-content {
    justify-content: center;
  }

  .chart-card {
    height: 300px;
  }

  .malicious-log {
    height: 250px;
  }

  .log-container {
    height: 200px;
  }

  .overview-section {
    margin-top: 10px;
  }
}
</style>